package com.ruoyi.common.utils;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;

public class AESUtil {
    private static final String ALGORITHM = "AES";
    private static final String FIXED_KEY = "12345678901234567890123456789012"; // 32 字节或 256 位

    // 生成一个随机密钥（在实际应用中，应妥善存储这个密钥）
    public static SecretKey generateKey() throws Exception {
        KeyGenerator keyGen = KeyGenerator.getInstance(ALGORITHM);
        keyGen.init(128);
        return keyGen.generateKey();
    }

    // 使用固定密钥
    private static SecretKey getSecretKey() {
        byte[] keyBytes = FIXED_KEY.getBytes();
        return new SecretKeySpec(keyBytes, ALGORITHM);
    }

    // 加密
    public static String encrypt(String data) throws Exception {
        SecretKey key = getSecretKey(); // 获取固定密钥
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, key);
        byte[] encrypted = cipher.doFinal(data.getBytes());
        return Base64.getEncoder().encodeToString(encrypted);
    }

    // 解密（可选，通常在服务端实现）
    public static String decrypt(String encryptedData, SecretKey key) throws Exception {
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, key);
        byte[] decoded = Base64.getDecoder().decode(encryptedData);
        byte[] original = cipher.doFinal(decoded);
        return new String(original);
    }
}
